<template>
  <view>
    <view class="page-content">
      <u-cell-group>
        <u-cell-item
          title="头像"
          :arrow="false"
          @click="cellClick('头像', 'profilePhoto', 'headphoto')"
        >
          <template #right-icon>
            <!-- <u-icon
              name="touxiang"
              custom-prefix="custom-icon"
              color="#999"
              :size="50"
            ></u-icon> -->
            <u-avatar
              v-if="formModal.profilePhoto"
              :size="50"
              :src="imageUrlPrefix + formModal.profilePhoto"
            ></u-avatar>
            <view v-else class="white-text">
              <u-avatar
                :size="50"
                bg-color="#ccc"
                :text="getNameShort(formModal?.name, 'last')"
              ></u-avatar>
            </view>
          </template>
        </u-cell-item>
        <u-cell-item
          title="姓名"
          :value="formModal.name || '请输入'"
          @click="cellClick('姓名', 'name')"
        ></u-cell-item>
        <u-cell-item
          title="性别"
          :value="getEchoValue(formModal.sex, seleceList.sex) || '请选择'"
          @click="cellClick('性别', 'sex', 'select')"
        ></u-cell-item>
        <u-cell-item
          title="手机号"
          :value="formModal.mobile || '请输入'"
          :arrow="false"
        ></u-cell-item>
        <u-cell-item
          title="邮箱"
          :value="formModal.email || '请输入'"
          @click="cellClick('邮箱', 'email')"
        ></u-cell-item>
        <u-cell-item
          title="民族"
          :value="
            getEchoValue(
              formModal.nominalTypeId,
              seleceList.nominalTypeId,
              'radio',
              {
                value: 'dictDataId',
                label: 'name',
              }
            ) || '请选择'
          "
          @click="cellClick('民族', 'nominalTypeId', 'select')"
        ></u-cell-item>
        <u-cell-item
          title="出生日期"
          :value="formModal.birthday || '请选择日期'"
          @click="cellClick('出生日期', 'birthday', 'select')"
        ></u-cell-item>
        <!-- <u-cell-item
          title="身份证号码"
          :value="formModal.idCard || '请输入'"
          @click="cellClick('身份证号码', 'idCard')"
        ></u-cell-item> -->
        <u-cell-item
          title="职称"
          :value="
            getEchoValue(
              formModal.titleTypeId,
              seleceList.titleTypeId,
              'radio',
              {
                value: 'dictDataId',
                label: 'name',
              }
            ) || '请选择'
          "
          @click="cellClick('职称', 'titleTypeId', 'select')"
        ></u-cell-item>
        <u-cell-item
          title="最高学历"
          :value="
            getEchoValue(
              formModal.highestEducationId,
              seleceList.highestEducationId,
              'radio',
              {
                value: 'dictDataId',
                label: 'name',
              }
            ) || '请选择'
          "
          @click="cellClick('最高学历', 'highestEducationId', 'select')"
        ></u-cell-item>
        <u-cell-item
          title="获取最高学历的学校"
          :value="formModal.highestDegreeSchool || '请输入'"
          @click="cellClick('获取最高学历的学校', 'highestDegreeSchool')"
        ></u-cell-item>
        <u-cell-item
          title="学术专业"
          :value="
            getEchoValue(
              formModal.professionType,
              seleceList.professionType,
              'mutil'
            ) || ''
          "
          :value-style="{ 'padding-left': '40rpx' }"
          :arrow="false"
        ></u-cell-item>
        <u-cell-item
          title="任职单位"
          :value="formModal.orgName"
          :value-style="{ 'padding-left': '40rpx' }"
          :arrow="false"
        ></u-cell-item>
      </u-cell-group>
    </view>
    <view class="btn-box">
      <u-button shape="circle" type="error" plain @click="loginOut"
        >退出登录</u-button
      >
    </view>
    <!--编辑输入型字段-->
    <!-- <editFeildVue ref="refEditFeildVue" :info="formModal" @success="getInfo" /> -->
    <!--编辑选择型字段-->
    <editSelectFeildVue
      ref="refEditSelectFeildVue"
      :info="formModal"
      @submit="submit"
    />

    <!--隐私条款及服务条款-->
    <u-modal
      v-model="show"
      :show-cancel-button="false"
      :mask-close-able="false"
      confirm-text="我已阅读并同意"
      @confirm="confirm"
    >
      <template #default>
        <view class="u-p-20 u-text-center">
          请阅读<text class="primary" @click="preview('3254959352456413188')"
            >《隐私条款》</text
          >及<text class="primary" @click="preview('3254959352506744839')"
            >《服务条款》</text
          >
        </view>
      </template>
    </u-modal>
  </view>
</template>
<script lang="ts" setup>
import { getNameShort } from '@/utils/tools';
import {
  getUserInfoById,
  getDictdata,
  logoutToken,
  uploadProfilePhoto,
} from '@/api/modules/user';
import { useUserStoreWidthOut } from '@/stores/user';
import editFeildVue from './editFeild.vue';
import editSelectFeildVue from './editSelectFeild.vue';
import { sexList, getEchoValue, getValueIndex } from '../index';
import { CascaderOptions } from '../data';
import { updateCurrUser } from '@/api/modules/user';
import { onShow, onUnload } from '@dcloudio/uni-app';
import { useBack } from '@/hooks/useBack';
import { useUserStore } from '@/stores/user';
import { getUploadUrl, getBaseUrl } from '@/utils/env';

const userStore = useUserStore();
const orgInfo = userStore.getOrgInfo;
const asyncUser = useUserStoreWidthOut();
const userInfo: any = asyncUser.getUserInfo;
const seleceList = ref<any>({
  sex: sexList,
  professionType: CascaderOptions,
});

const basicModelFlag = uni.getStorageSync('basicModelFlag') ?? true;
const show = ref(basicModelFlag);
const imageUrlPrefix =
  getBaseUrl() + '/doc/Rest/doc/file/filePreview' + '?docId=';

const preview = (id: string) => {
  const timestamp = new Date().getTime();
  const href =
    'https://ow365.cn/?i=17462&ssl=1&furl=' +
    `${getUploadUrl()}/Rest/doc/file/filePreview?timestamp=${timestamp}&orgId=${
      orgInfo.orgId
    }&docId=${id}`;
  uni.setStorageSync('signHref', href);
  (uni as any).$Router.push({
    name: 'autograph',
  });
};

const confirm = () => {
  uni.setStorageSync('basicModelFlag', false);
};

const formModal = ref<any>({});
const getInfo = () => {
  getUserInfoById({ userId: userInfo.userId }).then((res: any) => {
    formModal.value = res;
    formModal.value.orgName = res.insideOrgList
      .map((item: any) => item.orgName)
      .join('，');
  });
};

onUnload(() => {
  uni.$off('uAvatarCropper');
});

uni.$on('uAvatarCropper', (path) => {
  uni.uploadFile({
    url: `${getBaseUrl()}/doc/Rest/doc/file/minioDocUpload/false`,
    filePath: path,
    name: 'file',
    header: {
      'yootrial-account': '0',
      'yootrial-app': '0',
      'yootrial-timestamp': Date.now(),
      'yootrial-signature': '0',
      Authorization: userStore.getToken,
    },
    formData: {
      savePath: '目录01',
      bucket: 'yootrial-ctms',
    },
    success: (res) => {
      const data: any = JSON.parse(res.data);
      console.log(res);
      const params = {
        userId: formModal.value.userId,
        profilePhoto: data.data,
      };
      uploadProfilePhoto(params).then(() => {
        getInfo();
      });
    },
  });
});

const refEditFeildVue = ref();
const refEditSelectFeildVue = ref();
const cellClick = (title: string, feild: string, type = 'text') => {
  if (type === 'headphoto') {
    (uni as any).$Router.push({
      name: 'avatarCropper',
      params: {
        // 输出图片宽度，高等于宽，单位px
        destWidth: 300,
        // 裁剪框宽度，高等于宽，单位px
        rectWidth: 200,
        // 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
        fileType: 'jpg',
      },
    });
  } else if (type === 'text') {
    (uni as any).$Router.push({
      name: 'editFeild',
      params: {
        feild,
        title,
        params: encodeURIComponent(JSON.stringify(formModal.value)),
      },
    });
  } else if (feild === 'birthday') {
    refEditSelectFeildVue.value.showSelect(
      [],
      feild,
      'picker',
      formModal.value[feild]
    );
  } else {
    let props = undefined;
    if (
      ['highestEducationId', 'titleTypeId', 'nominalTypeId'].includes(feild)
    ) {
      props = { value: 'dictDataId', label: 'name' };
    }
    refEditSelectFeildVue.value.showSelect(
      seleceList.value[feild],
      feild,
      'select',
      feild === 'professionType'
        ? formModal.value[feild]
        : getValueIndex(formModal.value[feild], seleceList.value[feild]),
      props
    );
  }
};

// 退出登录
const loginOut = async () => {
  // 询问用户是否退出登录
  uni.showModal({
    title: '提示',
    content: '确认退出登录吗？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        await logoutToken();
        asyncUser.setUserInfo({});
        asyncUser.setToken('');
        uni.removeStorageSync('Token');
        uni.reLaunch({
          url: '/pages/login/index',
        });
      }
    },
  });
};

const submit = (data: any) => {
  updateCurrUser(data)
    .then(() => {
      uni.showToast({
        title: '修改成功',
        icon: 'none',
        duration: 2000,
      });
      getInfo();
    })
    .finally(() => {});
};

onMounted(() => {
  getInfo();
  seleceList.value.nominalTypeId = [];
  seleceList.value.titleTypeId = [];
  seleceList.value.highestEducationId = [];
  getDictdata({ flag: 'NOMINAL_TYPE,TITLE_TYPE,HIGH_EDUCATION_TYPE' })
    .then((res: any) => {
      seleceList.value.nominalTypeId = res.NOMINAL_TYPE;
      seleceList.value.titleTypeId = res.TITLE_TYPE;
      seleceList.value.highestEducationId = res.HIGH_EDUCATION_TYPE;
    })
    .catch(() => {});
});

useBack(() => getInfo());
</script>
<style lang="scss">
// page {
//   width: 100%;
//   height: 100%;
//   box-sizing: border-box;
//   position: relative;
//   background: #fff;
// }
.page-content {
  padding-bottom: calc(env(safe-area-inset-bottom) + 140rpx);
  width: 100%;
  height: 100%;
}
.btn-box {
  bottom: 0;
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
  position: fixed;
  // bottom: 0;
  z-index: 10;
}
.white-text {
  .u-avatar {
    color: #fff !important;
    text {
      font-size: 32rpx !important;
    }
  }
}
</style>
